import ESUtils.ESClientUtil;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.util.HashMap;

/**
 * 复杂查询
 */
public class EsTest02 {
    /**
     * 批量添加
     */
    @Test
    public void testAdd(){
        //1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        for (int i = 0; i <= 99; i++) {
            //2.创建索引和类型
            IndexRequestBuilder index = client.prepareIndex("pethome", "pet", "1" + i);
            //3.创建一个map来装数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", 1 + i);
            map.put("name", "江糖");
            map.put("sex", i % 2);
            map.put("age", 2 + i);
            System.out.println(index.setSource(map).get());
        }
        client.close();
    }

    /**
     * 复杂查询
     * 条件
     * - 查询用户表
     * - name包含：江糖
     * - age在1~50之间
     * - sex=0
     * - 每页大小3
     * - 从2页开始查
     * - 按照age倒序
     * query{
     *     bool{
     *         must:{
     *             macth
     *         },
     *         filter:[
     *         {term{}}
     *         {range{}}
     *         ]
     *     },
     *     size:
     *     from:
     *     sort:
     * }
     */
    @Test
    public void testLoad(){
        //获取ES连接
        TransportClient client = ESClientUtil.getClient();
        //查询
        SearchRequestBuilder pethome = client.prepareSearch("pethome");
        //bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //must
        boolQueryBuilder.must(QueryBuilders.matchQuery("name","江糖"));
        //filter
        boolQueryBuilder.filter(QueryBuilders.termQuery("sex",0))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(50));
        //开启复杂查询
        SearchRequestBuilder searchRequestBuilder = pethome.setQuery(boolQueryBuilder);
        //size,from,sort
        searchRequestBuilder.setSize(3).setFrom(3).addSort("age", SortOrder.DESC);
        //获取查询到的文档信息：是一个数组
        SearchHit[] hits = searchRequestBuilder.get().getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
